define(function(require, exports) {
	var $ = require("jquery");
	var pubjs = require('pubjs');
	var popwin = require('@base/dialog').base;
	var util = require('util');

	var Product = popwin.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				'title': LANG('选择广告位'),
				'width': 1050,
				'class': 'P-AdPositionSelect',
				'silence': false,
				// 是否实时发送变更消息（选择变化时会立即发送消息）
				'realtime': true,
				'view_model': {
					'isAddMode': false,
					'showSelected': false,
					'evAddPosition': this.eventAddPosition
				},
				"param": {
					'Type': 2
				},
				'url': {
					// 媒体dropdown
					'media': 'massMedia/list',
					// 广告位列表
					'grid': 'spot/monitorList'
				},
				'size': 'xl'
			});

			this.$data = {};
			this.Super('init', arguments);
		},
		afterBuild: function() {
			this.Super('afterBuild', arguments);
			var c = this.getConfig();
			var el = this.getDOM('body');
			var cls = this.getConfig('class');
			el.addClass(cls);
			el.append($([
				'<div class="selectAdWrap">',
					'<div class="selectivePage" ms-visible="!isAddMode">',
						'<div class="media-wrap">',
							'<label class="mr10">'+ LANG('选择媒体') +'</label>',
							'<div class="dib" pub-name="media" pub-mod="@base/common/dropdown.base" />',
						'</div>',
						'<div class="pr mt15">',
							'<div class="right-ctrl pa top-right z99">',
								'<div class="selected">',
									'<label for="showselect" class="cur_p mr15">',
										'<input type="checkbox" ms-duplex-radio="showSelected" />',
										'<span>'+ LANG('显示已选') +'</span>',
									'</label>',
									'<button ms-click="evAddPosition" class="btn btn-primary">' + LANG('新建广告位') + '</button>',
								'</div>',
							'</div> ',
							'<div pub-name="grid" pub-mod="@base/grid.base"></div>',
						'</div>',
					'</div>',

					'<div class="addedPage" ms-visible="isAddMode">',
						'<div class="animated" >',
							'<div pub-name="form" pub-mod="ads/action/edit.add"></div>',
						'</div>',
					'</div>',
				'</div>'
			].join('')));

			this.$animate = el.find('.animated');

			var config = {
				'media': {
					'module': '@base/common/dropdown.base',
					'def': LANG('所有媒体'),
					'width': 300,
					'reqType': 'websocket',
					'option_render': this.renderOptionItem,
					'url': c.url.media,
					'key': '_id',
					'name': 'Name',
					'param': {Type: c.param.Type}
				},
				'grid': {
					'operation': {
						width: 120,
						render: this.renderOperation.bind(this)
					},
					'url': c.url.grid,
					'param': c.param,
					'cols': [
						// {type: 'id'},
						{name: '_id', text: 'ID', width: 60, align: 'center', sort: true},
						{type: 'index', name: 'ads_name', width: 250, render: 'renderName'},
						{name: 'ads_size', width: 150},
						{name: 'ads_price', width: 150},
						{name: 'ads_type', format: 'formatAdType', width: 150}
					],
					'sort': "_id",
					'reqType': 'websocket',
					'opClick': true,
					'hasTab': false,
					'hasPager': true,
					'hasSearch': true,
					'hasExport': false,
					'hasAmount': false,
					'auto_load': false,
					'limit': 8,
					'pager': {
						'size': 8,
						'showJumper': 0,
						'showSizeTypes': 0
					}
				},
				'form': {
					'height': 500,
					'showTitle': false,
					'showButton': false,
					'allowModifyChannel': false
				}
			};

			this.buildFromTemplate(config);
		},
		afterBuildTemplate: function() {
			this.vm.watch('showSelected', this.showSelect);
		},
		/**
		 * 下拉框渲染回调函数
		 */
		renderOptionItem: function(id, opt, dom) {
			var url = opt.Url || '-';
			var name = opt.Name || '-'
			url = url.replace(/^http[s]?:\/\//i, '');
			url = url.split('/').shift();
			$('<em style="float:right"/>').text(url).appendTo(dom);
			$('<b/>').text(name).appendTo(dom);
		},
		renderName: function(i, val, row, con) {
			return $('<a class="M-tableListWidthLimit"/>').attr({
				'title': val
			}).text(val).width(con.width);
		},
		formatAdType: function(val) {
			var types = [null, LANG('固定'), LANG('富媒体'), LANG('对联'), LANG('视频'), LANG('弹窗')];
			return types[val] || LANG('其他');
		},
		renderOperation: function(index, val, row) {
			var id = +row['_id'];
			var cls = 'btn btn-default';
			var title = LANG('添加');
			if (this.$data[id]) {
				cls = 'btn btn-success';
				title = LANG('取消');
			}
			return '<input data-op="select" type="button" class="' + cls + '" value="' + title + '" />';
		},
		// 显示已选
		showSelect: function() {
			var ids = null;
			if (this.vm.$.showSelected) {
				ids = util.keys(this.$data, function(key) {
					return +key;
				});
				ids = ids.join(',');
			}
			this.$.grid.setParam({
				ids: ids
			});
			this.$.grid.reload();
		},
		eventAddPosition: function() {
			this.switchMode('add');
			this.update();
		},
		/**
		 * 切换媒体过滤
		 */
		onOptionChange: function(ev) {
			var media_id = ev.param.id;
			this.$.grid.setParam({
				MassMediaId: media_id
			}).load();
			return false;
		},
		onListOpClick: function(ev) {
			var c = this.getConfig();
			var dom = ev.param.el;
			var data = ev.param.data;
			var id = +ev.param.data._id;

			// 添加
			if (dom.hasClass('btn-default')) {
				dom.removeClass('btn-default').addClass('btn-success').val(LANG('取消'));
				this.$data[id] = data;

			// 删除
			} else {
				dom.removeClass('btn-success').addClass('btn-default').val(LANG('添加'));

				if (id in this.$data) {
					delete this.$data[id];
				}
			}

			if (c.realtime) {
				this.fire('selectAdPosition', this.getValue());
			}
			return false;
		},
		onSaveSuccess: function(ev) {
			var self = this;
			util.each(ev.param.data, function(item) {
				var id = item._id;
				self.$data[id] = item;
				self.fire('selectAdPosition', self.getValue());
			});
			self.$.grid.updateOperation();

			//新建创意包页面
			self.onCancel();
			return false;
		},
		switchMode: function(mode) {
			var self = this;
			var vm = self.vm.$;
			var param = self.$param;
			switch (mode) {
				case 'list':

					self.$.grid.reload();

					vm.isAddMode = false;
					// 动画效果-移出
					self.$animate.hide();

					// // 更新标题名字
					self.setTitle(LANG('选择广告位'));

					break;
				case 'add':
					vm.isAddMode = true;
					// XXX: 广告位编辑需要同时传入渠道id和名称
					if(self.$.form){
						self.$.form.reset().setData({
							ChannelId: param.ChannelId,
							AdSubChannelName: param.ChannelName
						});
					}
					// 动画效果-移进
					self.$animate.show();

					// 更新标题名称
					self.setTitle(LANG('新建广告位'));

					break;
				default:
					return false;
			}
			return true;
		},
		onCancel: function() {
			//新建创意包页面
			var vm = this.vm.$;
			if (vm.isAddMode) {
				//重置到选择创意包页面
				this.switchMode('list');
				this.$.grid.load();
			} else {
				this.hide();
			}
			return false;
		},
		onOk: function() {
			var self = this;

			if (self.vm.$.isAddMode) {
				self.$.form.save();
				self.$.grid.setParam({
					'MassMediaId': null
				});
				self.$.media.load();
			} else {
				self.hide();
				self.fire('selectAdPositionOk', self.getValue());
			}
			return false;
		},
		load: function() {
			this.$.media.load();
			this.$.grid.reload();
			return this;
		},
		setParam: function(param, replace) {
			this.$param = param;
			this.$.grid.setParam(param, replace);
			this.$.media.setParam(param, replace);
			return this;
		},
		// 设置选中的项
		setValue: function(list) {
			var data = {};
			util.each(list, function(item) {
				var id = item;
				if (item && item._id) {
					id = item._id;
				}
				data[id] = item;
			});
			this.$data = data;
			this.$.grid.updateOperation();
			return this;
		},
		getValue: function() {
			return this.$data;
		},
		reset: function() {
			this.$.grid.setParam({}, true);
			this.$.media.reset();
			return this;
		},
		reload: function() {
			this.$.grid.reload();
			return this;
		},
		onUpateMediaData: function(ev){
			this.$.media.load();
		}
	});

	exports.base = Product;

});